package de.slothsoft.commons.swing;

import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;

public class ArrayComboBoxModel<A> extends AbstractListModel<A> implements
		ComboBoxModel<A> {

	private static final long serialVersionUID = 1L;

	private final A[] array;
	private boolean addNullElement;
	private Object selected;

	public ArrayComboBoxModel(A[] array, boolean addNullElement) {
		this.array = array;
		this.addNullElement = addNullElement;
	}

	public boolean isAddNullElement() {
		return this.addNullElement;
	}

	public void setAddNullElement(boolean addNullElement) {
		this.addNullElement = addNullElement;
	}

	public A[] getArray() {
		return this.array;
	}

	@Override
	public int getSize() {
		return this.array.length + (isAddNullElement() ? 1 : 0);
	}

	@Override
	public A getElementAt(int index) {
		if (index == 0 && this.addNullElement) {
			return null;
		}
		return this.array[index - (this.addNullElement ? 1 : 0)];
	}

	@Override
	public void setSelectedItem(Object anItem) {
		this.selected = anItem;
	}

	@Override
	public Object getSelectedItem() {
		return this.selected;
	}

}
